package com.hw.pusher.stream;

import com.hw.pusher.utils.Logger;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;
import io.flutter.view.FlutterView;

public class FlutterEventChannel implements EventChannel.StreamHandler {

    private static final String EVENT_CHANNEL_NAME = "com.hw.pusher/stream";
    private EventChannel.EventSink eventSink;


    private FlutterEventChannel(FlutterEngine flutterEngine) {
        EventChannel eventChannel = new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), EVENT_CHANNEL_NAME);
        eventChannel.setStreamHandler(this);
    }

    public static FlutterEventChannel create(FlutterEngine flutterEngine) {
        return new FlutterEventChannel(flutterEngine);
    }

    public void sendEvent(Object data) {
        if (null != eventSink) {
            eventSink.success(data);
        } else {
            Logger.d("FlutterEventChannel sendEvent : eventSink is null.");
        }
    }

    public boolean registered() {
        if (null != eventSink) {
            return true;
        }
        return false;
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        this.eventSink = events;
    }

    @Override
    public void onCancel(Object arguments) {
        eventSink = null;
    }
}
